package com.yan.demo5;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author taoge
 * @Date 2024/8/15 10:46
 * @Description
 */
public class Demo5 {
    public static void main(String[] args) throws IllegalAccessException {
        Book book = new Book("红楼梦", new Date());
        Class c = Book.class;
        Field[] declaredFields = c.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            if(declaredField.isAnnotationPresent(MyJsomFormat.class)){
                MyJsomFormat annotation = declaredField.getAnnotation(MyJsomFormat.class);
                String pattern = annotation.pattern();
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                Date date = (Date) declaredField.get(book);
                String format = sdf.format(date);
                System.out.println("format = " + format);
            }

        }
    }
}

class Book{
    private String name;
    @MyJsomFormat(pattern = "yyyy-MM-dd")
    private Date createDate;

    public Book() {
    }

    public Book(String name, Date createDate) {
        this.name = name;
        this.createDate = createDate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Book book = (Book) o;

        if (name != null ? !name.equals(book.name) : book.name != null) return false;
        return createDate != null ? createDate.equals(book.createDate) : book.createDate == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (createDate != null ? createDate.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", createDate=" + createDate +
                '}';
    }
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyJsomFormat{
    String pattern();
}

